package com.cn.lyl.service.impl;

import com.cn.lyl.dao.NewsDao;
import com.cn.lyl.dao.NewsTypeDao;
import com.cn.lyl.dao.NewsTypeDependenceDao;
import com.cn.lyl.dao.impl.NewsDaoImpl;
import com.cn.lyl.dao.impl.NewsTypeDaoImpl;
import com.cn.lyl.dao.impl.NewsTypeDependenceDaoImpl;
import com.cn.lyl.model.NewsModel;
import com.cn.lyl.model.NewsTypeDependenceModel;
import com.cn.lyl.model.NewsTypeModel;
import com.cn.lyl.service.NewsService;

import java.util.List;

public class NewsServiceImpl implements NewsService {
    @Override
    public List<NewsModel> findAllNews(NewsModel newsModel) {
        NewsDao newsDao = new NewsDaoImpl();
        return newsDao.findAll(newsModel);
    }

    @Override
    public int getCount(NewsModel newsModel) {
        NewsDao newsDao = new NewsDaoImpl();
        return newsDao.countFindAll(newsModel);
    }

    @Override
    public String addNews(NewsModel newsModel) {
        NewsDao newsDao = new NewsDaoImpl();
        NewsTypeDao newsTypeDao = new NewsTypeDaoImpl();
        NewsTypeDependenceDao newsTypeDependenceDao = new NewsTypeDependenceDaoImpl();
        NewsTypeModel type= new NewsTypeModel();
        if(newsModel.getDependenceObj()==null){
            return newsDao.add(newsModel)>0?"success":"error";
        }
        int insert = newsDao.add(newsModel);
        type.setType((String) newsModel.getDependenceObj());
        NewsTypeModel byName = newsTypeDao.findByName(type);
        NewsModel newModel = newsDao.findNewest();
        NewsTypeDependenceModel model = new NewsTypeDependenceModel();
        model.setNewsId(newModel.getId());
        model.setTypeId(byName.getId());
        return (newsTypeDependenceDao.add(model)>0&&insert>0)?"success":"error";
    }

    @Override
    public String deleteNews(NewsModel newsModel) {
        NewsDao newsDao = new NewsDaoImpl();
        NewsTypeDependenceDao newsTypeDependenceDao = new NewsTypeDependenceDaoImpl();
        NewsTypeDependenceModel model = new NewsTypeDependenceModel();
        model.setNewsId(newsModel.getId());
        newsTypeDependenceDao.delete(model);
        return newsDao.delete(newsModel)>0?"success":"error";
    }

    @Override
    public NewsModel findInfo(int id) {
        NewsDao newsDao = new NewsDaoImpl();
        return newsDao.findById(id);
    }

    @Override
    public String changeInfo(NewsModel newsModel) {
        NewsDao newsDao = new NewsDaoImpl();
        return newsDao.update(newsModel)>0?"success":"error";
    }

    @Override
    public String changeHomeState(NewsModel newsModel) {
        NewsDao newsDao = new NewsDaoImpl();
        return newsDao.updateIsHome(newsModel)>0?"success":"error";
    }
}
